<!DOCTYPE html>
<html lang="en-US" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>部门管理</title>
<link rel="stylesheet" th:href="@{~/component/layui/css/layui.css}" media="all">
<link rel="stylesheet" th:href="@{~/component/pear/css/pear-module/dtree/dtree.css}" media="all">
<link rel="stylesheet" th:href="@{~/component/pear/css/pear-module/dtree/font/dtreefont.css}" media="all">
<link rel="stylesheet" th:href="@{~/component/pear/css/pear-module/treetable.css}" media="all">
<link rel="stylesheet" th:href="@{~/component/pear/css/pear-module/button.css}" media="all">
<link rel="stylesheet" th:href="@{~/common/css/common.css}" media="all">
</head>
<body style="overflow-y: hidden;" >
	<div class="my-header ">
		<div >
			<form class="layui-form layui-inline" name="searchForm">
				<div class="layui-input-inline">
				  <input type="text" name="name"  autocomplete="off" placeholder="请输入部门名称" class="layui-input">
				</div>
				<div class="layui-input-inline">
				  <input type="text" name="leader"  autocomplete="off" placeholder="请输入部门负责人" class="layui-input">
				</div>
				<div class="layui-input-inline">
				  <input type="text" name="phone"  autocomplete="off" placeholder="请输入部门负责人手机" class="layui-input">
				</div>
				<div class="layui-input-inline">
				  <select name="status">
			        <option value="">请选择部门状态</option>
			        <option value="1">正常</option>
			        <option value="0">禁用</option>
			      </select>
				</div> 
			
				<div style="margin-top: 16px;">
					<div class="layui-inline">
						<button sec:authorize="hasAuthority('sys:dept:select')" type="button" class="pear-btn pear-btn-success" lay-submit lay-filter="search" id="search"><i class="layui-icon layui-icon-search"></i> 查询</button>
					</div>
					<div class="layui-inline">
						<button sec:authorize="hasAuthority('sys:dept:select')" type="reset"  class="pear-btn pear-btn-warming" ><i class="layui-icon layui-icon-refresh"></i> 重置</button>
					</div>
					<!-- <div class="layui-inline">
						<button type="button" class="pear-btn pear-btn-primary" id="add"><i class="layui-icon layui-icon-addition"></i> 新增 </button>
					</div> -->
					<!-- <div class="layui-inline">
						<button type="button" class="pear-btn pear-btn-danger" id="batchDelete" ><i class="layui-icon layui-icon-delete"></i> 批量删除 </button>
					</div> -->
				</div>
			</form>
		</div>
	</div> 

<!-- 列表表格数据 -->
<table class="my-table" id="dept-table" lay-filter="dept-table"></table>

<!-- 展开/折叠 按钮 -->
<script type="text/html" id="dept-toolbar">
	<button class="pear-btn pear-btn-success pear-btn-md" lay-event="expandAll">
	    <i class="layui-icon layui-icon-spread-left"></i>
	    展开
	</button>
	<button class="pear-btn pear-btn-success pear-btn-md" lay-event="foldAll">
	    <i class="layui-icon layui-icon-shrink-right"></i>
	    折叠
	</button>
</script>

<!-- 列表工具：编辑、删除 -->
<script type="text/html" id="dept-bar">
	<button sec:authorize="hasAuthority('sys:dept:insert')" class="pear-btn pear-btn-success pear-btn-sm" lay-event="add" title="新增子部门"><i class="layui-icon layui-icon-add-1"></i></button>
	<button sec:authorize="hasAuthority('sys:dept:update')" class="pear-btn pear-btn-primary pear-btn-sm" lay-event="edit" title="编辑"><i class="layui-icon layui-icon-edit"></i></button>
	<button sec:authorize="hasAuthority('sys:dept:delete')" class="pear-btn pear-btn-danger pear-btn-sm" lay-event="delete" title="删除"><i class="layui-icon layui-icon-delete"></i></button>
</script>

<!-- 列表状态开关：0-禁用，1-正常 -->
<script type="text/html" id="dept-status">
	<input type="checkbox" id="{{d.id}}" name={{d.parentId}} value="{{d.status}}" lay-skin="switch" lay-text="正常|禁用"   lay-filter="dept-status"  {{ d.status == 1 ? 'checked' : '' }}>
</script>

<script th:src="@{~/component/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{~/component/pear/pear.js}" charset="utf-8"></script>
<script th:src="@{~/common/js/jquery-1.11.2.min.js}" charset="utf-8"></script>
<script type="text/javascript">
	
layui.use(['form', 'layedit', 'laydate','element','table','dtree','treetable'], function(){
	var $ = layui.jquery
	  ,form = layui.form
	  ,layer = layui.layer
	  ,laypage = layui.laypage
	  ,table = layui.table
	  ,dtree = layui.dtree
	  ,treetable = layui.treetable;
	
	var globalData = {};
	
	var flag = true; // 表格区分标志：true-树形表格，false-普通表格
	
	/* 渲染树形表格 */
	window.renderTreeTable = function(data){
		treetable.render({
		   treeColIndex: 0
		   ,treeSpid: 0 
		   ,treeIdName: 'id'
		   ,treePidName: 'parentId' 
		   //,skin:'line'
		  ,toolbar:true
		  ,treeDefaultClose: false
	      ,toolbar:'#dept-toolbar'
		  ,defaultToolbar: ['filter']
		  ,elem: '#dept-table' //指定原始表格元素选择器（推荐id选择器）
		  ,url: '/dept/list'
		  ,where: data
		  ,page: false
		  ,height: 'full-188' //容器高度
		  //设置表头
		  ,cols: [ [
			  	/* {checkbox: true} */
			    {field: 'name', title: '部门名称', align: 'center',style:'text-align:left' }
			    ,{field: 'leader', title: '部门负责人', align: 'center'}
			    ,{field: 'phone', title: '负责人手机', align: 'center',}
			    ,{field: 'status', title: '部门状态', align: 'center', templet: '#dept-status'}
			    ,{field: 'sort', title: '排序', align: 'center'}
			    ,{field: 'createTime', title: '创建时间', align: 'center',width:180}
			    ,{toolbar: '#dept-bar', title: '操作', minWidth: 120,  align: 'center',}
		  ]] 
		  
		});
	}
	
	// 渲染普通表格
	window.renderTable = function(data){
		table.render({
		  toolbar:true
	      ,toolbar:'#dept-toolbar'
		  ,defaultToolbar: ['filter']
		  ,elem: '#dept-table' //指定原始表格元素选择器（推荐id选择器）
		  ,url: '/dept/list'
		  ,where: data
		  ,page: false
		  ,height: 'full-188' //容器高度
		  //设置表头
		  ,cols: [ [
			  	/* {checkbox: true} */
			  	{type: 'numbers', title: '序号', width: 80, align: 'center',}
			    ,{field: 'name', title: '部门名称', align: 'center' }
			    ,{field: 'leader', title: '部门负责人', align: 'center'}
			    ,{field: 'phone', title: '负责人手机', align: 'center',}
			    ,{field: 'status', title: '部门状态', align: 'center', templet: '#dept-status'}
			    ,{field: 'sort', title: '排序', align: 'center'}
			    ,{field: 'createTime', title: '创建时间', align: 'center',width:180}
			    ,{toolbar: '#dept-bar', title: '操作', minWidth: 120,  align: 'center',}
		  ]] 
		  
		});
	}
	
	// 判断最终是渲染树形表格还是普通表格
	window.render = function(data){
		if(flag){
			renderTreeTable(data);
		}else{
			renderTable(data);
		}
	}
	
	render(globalData);
	
	/* 点击查询按钮 */
	form.on('submit(search)', function(res) {
		globalData = res.field;
		if(globalData.leader == '' && globalData.name == '' && globalData.phone == '' && globalData.status == ''){
			flag = true;
		}else{
			flag = false;
		}
		render(globalData);
		return false;
	});
	
	/* 工具条上的事件 */
	table.on('toolbar(dept-table)', function(obj) {
		if (obj.event === 'refresh') {
			render(globalData);
		}else if(obj.event === 'expandAll'){
			 treetable.expandAll("#dept-table");
		} else if(obj.event === 'foldAll'){
			 treetable.foldAll("#dept-table");
		}
	});
	
	/* 列表中的工具上的按钮事件 */
	table.on('tool(dept-table)', function(obj) {
		if (obj.event === 'delete') {
			window.delete(obj);
		} else if (obj.event === 'edit') {
			window.edit(obj);
		}else if (obj.event === 'add') {
			window.add(obj);
		}
	});
	
	
	/* 部门状态开关事件 */
	form.on('switch(dept-status)', function(obj) {
		var status = obj.elem.checked ? '1' : '0';
		var id = obj.elem.id;
		var parentId = obj.elem.name;
		var data = {"id":id,"status":status,"parentId":parentId}
		
		// 先判断该部门下是否存在子部门，如果存在子部门则提示对该部门的启用/禁用同时也会对子部门进行启用/禁用
		$.get("/dept/selectChildrenListById",{"id":id},function(result){
			console.log(result);
			if(result.code == 0){
				if(result.data.length > 1){
					layer.confirm('注意：该操作同时也会对子部门生效！', {
						  icon:7,
						  title:'提示',
						  btn: ['确定','取消'] //按钮
					}, function(){
						update(data);
					}, function(){
						render(globalData);
					});
				}else{
					if(status == 1){
						// 判断父部门状态是否正常，如果是禁用则无法进行启用状态
						$.get("/dept/selectById",{"id":parentId},function(result){
							if(result.code == 0){
								if(result.data.status == 0){
									layer.msg("父部门处于禁用状态，无法进行该操作",{icon:2,time:3000},function(){
										render(globalData);
									});
								}else if(result.data.status == 1){
									update(data);
								}
							}
						});
					}else{
						update(data);
					}
				}
			}else{
				layer.msg("服务器异常，请联系管理员",{icon:2,time:3000},function(){
					render(globalData);
				});
			}
		});
	});
	
	window.update = function(data){
		$.ajax({
            url:"/dept/updateStatusByParentId",
            data:JSON.stringify(data),
            contentType:'application/json',
            type:'post',
            success:function(result){
                if(result.code == 0){
                    layer.msg(result.msg,{icon:1,time:1000},function(){
                    	render(globalData);
                    });
                	
                }else{
                    layer.msg(result.msg,{icon:2,time:3000},function(){
                    	render(globalData);
                    });
                }
            }
        })
	}
	
    /* 点击编辑，弹出编辑页面 */
    window.edit = function(obj) {
		layer.open({
			type: 2,
			title: '修改部门信息',
			shade: 0.1,
			area: ['500px', '520px'],
			content: '/dept-edit?id='+obj.data.id
		});
	}
    
    window.add = function(obj) {
    	if(obj.data.status == 0){
    		layer.msg("禁用状态下无法新增子部门",{icon:2,time:3000});
    		return false;
    	}else if(obj.data.status == 1){
	    	layer.open({
	    		type: 2,
	    		title: '新增部门',
	    		shade: 0.1,
	    		area: ['500px', '520px'],
	    		content: '/dept-add?id='+obj.data.id
	    	});
    	}
	}
    
    /* 点击删除 */
    window.delete = function(obj) {
    	
    	if(obj.data.id == 1){
    		layer.msg('禁止删除总部机构',{icon:2,time:3000});
    		return false;
    	}
    	
		layer.confirm('确定要删除该部门【'+obj.data.name+'】', {
			icon: 3,
			title: '提示'
		}, function(index) {
			layer.close(index,{time: 5*1000});
			// 先判断该部门下是否存在子部门，如果存在子部门则提示对该部门的启用/禁用同时也会对子部门进行启用/禁用
			$.get("/dept/selectChildrenListById",{"id":obj.data.id},function(result){
				if(result.code == 0){
					if(result.data.length > 1){
						layer.confirm('注意：该操作同时也会对子部门生效！', {
							  icon:7,
							  title:'提示',
							  btn: ['确定','取消'] //按钮
						}, function(){
							del(obj);
						}, function(){
							render(globalData);
						});
					}else{
						del(obj);
					}
				}else{
					layer.msg("服务器异常，请联系管理员",{icon:2,time:3000},function(){
						render(globalData);
					});
				}
			});
			
			
			
		});
	}
    
    window.del = function(obj){
    	let loading = layer.load();
		let id = obj.data.id;
		$.post("/dept/delete",{"id":id},function(result){
			layer.close(loading);
            if(result.code == 0){
            	layer.msg(result.msg, {icon: 1,time: 1000}, function() {
					render(globalData);
				});
            }else{
                layer.msg(result.msg,{icon:2,time:3000});
            }
		});
    }
	
})

/* 点击添加按钮，弹出添加页面 */
$("#add").click(function(){
	layer.open({
		type: 2,
		title: '新增部门',
		shade: 0.1,
		area: ['500px', '520px'],
		content: '/dept-add'
	});
});



</script>

</body>
</html>